package com.zrb.mobile.utility;

import java.io.IOException;
import java.net.URI;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zrb.applib.utils.AppSetting;
import com.zrb.applib.utils.LocalUserInfo;
import com.zrb.mobile.MainTabActivity;
import com.zrb.mobile.R;
import com.zrb.mobile.User_app_setting;
 
import com.zrb.mobile.common.OnlineServer;
import com.zrb.mobile.register.User_phone_login;

public class ZrbRestClient extends AsyncHttpResponseHandler {
	
	//http://61.183.87.134:8090/information/informationList.jspx?pageSize=10&pageNum=9
	//http://61.183.87.134:8090/zrb/mobile/proList.jspx
	
	 //// called when response HTTP status is "4XX" (eg. 401, 403, 404)  onFailure
	  HttpResponseListener mhttpResponseListener;
	  private final static AsyncHttpClient client = new AsyncHttpClient();
	  RequestParams curAction;
	  String curServer;
	  boolean isPost=false;
	  Context mContext;
	  int refleshTick=0;
 
	  public ZrbRestClient(Context context){
		  
		  mContext=context;
	  }
	  
	  public static void getRoot(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
 		  String siteurl=  AppSetting.BASE_URL.substring(0, AppSetting.BASE_URL.indexOf("mobile"));
	      client.get(siteurl+url, params, responseHandler);
	  }
	  
	  
	  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
	      client.get(getAbsoluteUrl(url), params, responseHandler);
	  }

	  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
	      client.post(getAbsoluteUrl(url), params, responseHandler);
	  }
	  
	  public static void postfile(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
	      client.post(getFileAbsoluteUrl(url), params, responseHandler);
	  }

	  private static String getFileAbsoluteUrl(String relativeUrl) {
	      return AppSetting.mediaServer + relativeUrl;
	  }
	  
	  private static String getAbsoluteUrl(String relativeUrl) {
	      return AppSetting.BASE_URL + relativeUrl;
	  }
 	  
 	  public void getcheckSession(String url){
 		  isPost=false;
 		  get(getAbsoluteUrl(url),false);
	  } 
	  
	  public void sessionGet(String url){
  		  if(null==AppSetting.curUser){
  			  hiteError(R.string.user_center_account_conflict3);
 			  return;
		  }
		  isPost=false;
 		  get(getAbsoluteUrl(url),false);
	  }
 	 
	  private void get(String url,boolean isRefresh){
 		  curServer=url;
 		 if(url.contains("zrb_front_ut")) return;
 		  if(!url.contains("zrb_front_ut")&&null!=AppSetting.curUser) 
			  url+="&zrb_front_ut="+ AppSetting.curUser.zrb_front_ut;
 		 
 		  CommonUtil.InfoLog("mZrbRestClient:get", url);
  		  client.get(url, null, this);
	  }
 	  
	  public void post(String url,RequestParams params){
		  isPost=true;
		  post( getAbsoluteUrl(url), params, false);
	  }
	  
	  private void post(String url,RequestParams params,boolean isRefresh){
		  
		   curServer=url;
		   curAction=params;
  		   if(null!=AppSetting.curUser) 
			   params.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
  		 
		   CommonUtil.InfoLog("mZrbRestClient:post", url+"?"+params.toString());
		   client.post(url, params,this);
	  }
  	  
	  private void Refleshtoken(final boolean isPost){
			CommonUtil.InfoLog("mZrbRestClient", "Refleshtoken");
 			if(AppSetting.curUser==null) return;
			 
			RequestParams param = new RequestParams();
		 	param.put("uid", AppSetting.curUser.uid);
			param.put("password", AppSetting.curUser.pwd);  
 
			ZrbRestClient.post("doRefreshLogin", param,
					new AsyncHttpResponseHandler() {

						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
 							CommonUtil.InfoLog("0mZrbRestClient", "fail") ;
							hiteError(R.string.error_net_loadfail);
 						}

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
							// TODO Auto-generated method stub
	 					    String results = new String(arg2);
	 					    CommonUtil.InfoLog("1mZrbRestClient", "ok") ;
	 						JSONObject jsonObject2;
							try {
								jsonObject2 = new JSONObject(results);
								int retCode= jsonObject2.getInt("res");
 								if(retCode==1){
 									JSONObject tmpObj= jsonObject2.getJSONObject("data");
									AppSetting.curUser.zrb_front_ut=tmpObj.getString("zrb_front_ut");
									if(isPost)	
									    post(curServer,curAction,true);
									else
									    get(curServer,true);
  								}
 								else{
 									AppSetting.curUser=null;
 									LocalUserInfo.getInstance(mContext).clearUserInfo();
 									showDialog(R.string.user_center_account_conflict2);
   								}
 							} catch (JSONException e) {
				 
 								hiteError(R.string.error_serverdata_loadfail);
 								CommonUtil.InfoLog("Refleshtoken_error", e.getMessage());
				 
							}
  						}
					});
			
		}

	  
	  private void hiteError(int Resid){
 			if(null!=mhttpResponseListener)
				mhttpResponseListener.onFailure(Resid, null, null,null);
	  }
	  
	  
	  public void setOnhttpResponseListener(HttpResponseListener httpResponseListener){
 		  mhttpResponseListener=httpResponseListener;
	  }
	  
	  public interface	HttpResponseListener {
			
			 void onSuccess(int paramInt, Header[] paramArrayOfHeader, byte[] paramArrayOfByte);

			 void onFailure(int paramInt, Header[] paramArrayOfHeader, byte[] paramArrayOfByte, Throwable paramThrowable);
		}

	@Override
	public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
		// TODO Auto-generated method stub
  		if(null!=mhttpResponseListener)
			mhttpResponseListener.onFailure(R.string.error_net_loadfail, arg1, arg2,arg3);
	}


	@Override
	public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
		// TODO Auto-generated method stub
		 String results = new String(arg2);
		   try {
			JSONObject jsonObject2 =new JSONObject(results);
			int retCode= jsonObject2.getInt("res");
			switch(retCode){
			case 0:
			case 1:
				if(null!=mhttpResponseListener)
					mhttpResponseListener.onSuccess(arg0, arg1, arg2);
				break;
			case -1://超时
				refleshTick++;
				if(refleshTick<3) Refleshtoken(isPost);
				
				break;
			case -11://下线
				AppSetting.curUser=null;
				LocalUserInfo.getInstance(mContext).clearUserInfo();
				showDialog(R.string.user_center_account_conflict);
				break;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			if(null!=mhttpResponseListener)
				mhttpResponseListener.onFailure(R.string.error_serverdata_loadfail, arg1, arg2,null);
			e.printStackTrace();
		}
	}

 	 private void showDialog(int resId){
		 
		 new AlertDialog(mContext).builder().setTitle("系统提示")
		   .setMsg(resId)
		   .setCancelable(false)
		   .setPositiveButton("确定", new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent it = new Intent(mContext, User_phone_login.class);
				 mContext.startActivity(it);
			}
		    }).setNegativeButton("取消").show();
 		 
	 }
}
